package com.house365.core.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.RelativeLayout;

import com.house365.core.R;
import com.house365.core.adapter.BaseAlbumAdapter;
import com.house365.core.application.BaseApplication;
import com.house365.core.constant.CorePreferences;
import com.house365.core.touch.ImageViewTouch;
import com.house365.core.touch.ScaleGestureDetector;

/**
 * @author py
 * @date 2012-8-10
 * @comment a common album
 */
public class AlbumView extends RelativeLayout {

	public static final int LEFT = 0;
	public static final int TOP = 1;
	public static final int RIGHT = 2;
	public static final int BOTTOM = 3;
	public static final int CENTER_X = 4;
	public static final int CENTER_Y = 5;
	private Gallery gallery;

	private boolean useGallery =false;
	private float galleryWidth, galleryHeight, gallerySpacing,
			galleryPaddingLeft, galleryPaddingTop, galleryPaddingRight,
			galleryPaddingBottom;
	private int galleryPosition;
	private float pageMargin;
	private int pageMarginDrawable;
	private int pageMarginColor;
	
	private boolean mPaused;
	private boolean mOnScale = false;
	private boolean mOnPagerScoll = false;
	
	private Context context;
	// the view where picture show
	private ViewPager viewPager;
	
	private BaseAlbumAdapter adapter;
	protected BaseApplication application;
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			mOnScale = false;
		};
	};
	public AlbumView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		getAttr(context, attrs);
		init(context);
	}

	public AlbumView(Context context, AttributeSet attrs) {
		super(context, attrs);
		getAttr(context, attrs);
		init(context);
	}
	public AlbumView(Context context) {
		super(context);
		init(context);
	}

	private void getAttr(Context context, AttributeSet attrs) {
		TypedArray a = context.obtainStyledAttributes(attrs,
				R.styleable.AlbumView);
		galleryWidth = a.getDimension(R.styleable.AlbumView_galleryWidth, -1f);
		galleryHeight = a
				.getDimension(R.styleable.AlbumView_galleryHeight, -1f);
		gallerySpacing = a.getDimension(R.styleable.AlbumView_gallerySpacing,
				0f);
		galleryPaddingLeft = a.getDimension(
				R.styleable.AlbumView_galleryPaddingLeft, 0f);
		galleryPaddingTop = a.getDimension(
				R.styleable.AlbumView_galleryPaddingTop, 0f);
		galleryPaddingRight = a.getDimension(
				R.styleable.AlbumView_galleryPaddingRight, 0f);
		galleryPaddingBottom = a.getDimension(
				R.styleable.AlbumView_galleryPaddingBottom, 0f);

		pageMargin = a.getDimension(R.styleable.AlbumView_pageMargin, -1f);

		galleryPosition = a.getInt(R.styleable.AlbumView_galleryPosition,
				BOTTOM);

		pageMarginDrawable = a.getResourceId(
				R.styleable.AlbumView_pageMarginDrawable, -1);

		pageMarginColor = a.getColor(R.styleable.AlbumView_pageMarginColor, -1);
		
		useGallery = a.getBoolean(R.styleable.AlbumView_useGallery,false);
		a.recycle();

	}

	
	public void init(Context context) {
		this.context =context;
		application = (BaseApplication) context.getApplicationContext();
		// page attrs
		viewPager = new ViewPager(context);
		viewPager.setLayoutParams(new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.FILL_PARENT,
				RelativeLayout.LayoutParams.FILL_PARENT));
		if (pageMarginDrawable != -1) {
			viewPager.setPageMarginDrawable(pageMarginDrawable);
		}
		if (pageMarginColor != -1) {
			viewPager.setPageMarginDrawable(new ColorDrawable(pageMarginColor));
		}
		if (pageMargin != -1) {
			viewPager.setPageMargin((int) pageMargin);
		}
		showAnimation = new AlphaAnimation(0f, 1f);
		showAnimation.setFillAfter(true);
		showAnimation.setDuration(SHOW_HIDE_CONTROL_ANIMATION_TIME);

		hideAnimation = new AlphaAnimation(1f, 0f);
		hideAnimation.setFillAfter(true);
		hideAnimation.setDuration(SHOW_HIDE_CONTROL_ANIMATION_TIME);
		
		this.addView(viewPager);
		if(useGallery){
			// gallery attrs
			gallery = new Gallery(context);
			RelativeLayout.LayoutParams galleryLayout = new RelativeLayout.LayoutParams(
					galleryWidth > 0 ? (int) galleryWidth
							: RelativeLayout.LayoutParams.FILL_PARENT,
					galleryHeight > 0 ? (int) galleryHeight
							: RelativeLayout.LayoutParams.FILL_PARENT);
			galleryLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
			gallery.setLayoutParams(galleryLayout);
			gallery.setPadding((int) galleryPaddingLeft, (int) galleryPaddingTop,
					(int) galleryPaddingRight, (int) galleryPaddingBottom);
			gallery.setSpacing((int) gallerySpacing);
			this.addView(gallery);
		}
		viewPager.setOnPageChangeListener(mPageChangeListener);
		setupOnTouchListeners(viewPager);
		
		hideControls();
	}

	private static final int SHOW_HIDE_CONTROL_ANIMATION_TIME = 500;
	private AlphaAnimation showAnimation;
	private boolean isFullScreen = false;
	private AlphaAnimation hideAnimation;
	private GestureDetector mGestureDetector;
	private ScaleGestureDetector mScaleGestureDetector;
	
	private int currPos;
	private int prePos;
	private AlumViewListener alumViewListener;
	private void showControls() {
		if(useGallery){
			gallery.startAnimation(showAnimation);
			gallery.setVisibility(View.VISIBLE);
		}

		isFullScreen = false;
	}

	private void hideControls() {
		if(useGallery){
			gallery.startAnimation(hideAnimation);
			gallery.setVisibility(View.GONE);
		}
		isFullScreen = true;
	}
	public void setAdapter(BaseAlbumAdapter adapter) {
		this.adapter = adapter;
		viewPager.setAdapter(adapter.getPageAdapter());
		if(useGallery){
			gallery.setAdapter(adapter.getGalleryAdapter());
			gallery.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					setCurrentPosition(position);
				}
			});
			adapter.setGallery(gallery);
		}	
		
		
	}
	public ImageViewTouch getCurrentImageView(){
		return adapter.getImageView(currPos);
	}
	ViewPager.OnPageChangeListener mPageChangeListener = new ViewPager.OnPageChangeListener() {


		@Override
		public void onPageSelected(int position) {
			
			ImageViewTouch preImageView = null;
			try {
				if(prePos != position && prePos>=0){
					preImageView = adapter.getImageView(position);
				}
				
			} catch (Exception e) {
			}
			if (preImageView != null) {
				preImageView.setImageBitmapResetBase(
						preImageView.mBitmapDisplayed.getBitmap(), true);
			}
			currPos = position;
			setCurrentPosition(position);
			if(alumViewListener!= null){
				alumViewListener.onChange(currPos);
			}
			
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
			mOnPagerScoll = true;
		}

		@Override
		public void onPageScrollStateChanged(int state) {
			if (state == ViewPager.SCROLL_STATE_DRAGGING) {
				mOnPagerScoll = true;
			} else if (state == ViewPager.SCROLL_STATE_SETTLING) {
				mOnPagerScoll = false;
			} else {
				mOnPagerScoll = false;
			}
		}


	
		
	};
	private void setupOnTouchListeners(View rootView) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
			mScaleGestureDetector = new ScaleGestureDetector(context,
					new MyOnScaleGestureListener());
		}
		mGestureDetector = new GestureDetector(context, new MyGestureListener());

		OnTouchListener rootListener = new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {

				if(event.getAction()==MotionEvent.ACTION_UP){
					mOnPagerScoll=false;
				}
				
				try{
					CorePreferences.DEBUG("mOnScale:"+mOnScale+",mOnPagerScoll:"+mOnPagerScoll);
				if (!mOnScale) {
					if (!mOnPagerScoll) {
						mGestureDetector.onTouchEvent(event);
					}
				}

				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
					if (!mOnPagerScoll && event.getPointerCount() >= 2) {
						mScaleGestureDetector.onTouchEvent(event);
					}
				}

				ImageViewTouch imageView = getCurrentImageView();
				if (!mOnScale) {
					Matrix m = imageView.getImageViewMatrix();
					RectF rect;
					if (imageView.mBitmapDisplayed.getBitmap() != null) {
						rect = new RectF(0, 0, imageView.mBitmapDisplayed
								.getBitmap().getWidth(),
								imageView.mBitmapDisplayed.getBitmap()
										.getHeight());
					} else {
						rect = new RectF(0, 0,
								application.getMetrics().widthPixels,
								application.getMetrics().heightPixels);
					}

					m.mapRect(rect);
					if (!(rect.right > imageView.getWidth() + 0.1 && rect.left < -0.1)) {
						try {
							viewPager.onTouchEvent(event);
						} catch (ArrayIndexOutOfBoundsException e) {
						}
					}
				}
				}catch(Exception e){
					CorePreferences.ERROR(e);
				}
				return true;
			}
		};

		rootView.setOnTouchListener(rootListener);
	}
	private class MyGestureListener extends
			GestureDetector.SimpleOnGestureListener {

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {
			if (mOnScale) {
				return true;
			}
			if (mPaused) {
				return false;
			}
			Log.d("MyGestureListener2", "e1:" + e1);
			ImageViewTouch imageView = getCurrentImageView();
			imageView.panBy(-distanceX, -distanceY);
			imageView.center(true, true);
			return true;
		}


		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			if (isFullScreen) {
				showControls();
			} else {
				hideControls();
			}
			if(alumViewListener!= null){
				alumViewListener.onFullScreen(isFullScreen, currPos);
			}
			return true;
		}

		@Override
		public boolean onDoubleTap(MotionEvent e) {
			if (mPaused) {
				return false;
			}
			ImageViewTouch imageView = getCurrentImageView();
			if (imageView.mBaseZoom < 1) {
				if (imageView.getScale() > 2F) {
					imageView.zoomTo(1f);
				} else {
					imageView.zoomToPoint(3f, e.getX(), e.getY());
				}
			} else {
				if (imageView.getScale() > (imageView.mMinZoom + imageView.mMaxZoom) / 2f) {
					imageView.zoomTo(imageView.mMinZoom);
				} else {
					imageView.zoomToPoint(imageView.mMaxZoom, e.getX(),
							e.getY());
				}
			}
			return true;
		}
	}
	
	private class MyOnScaleGestureListener extends
			ScaleGestureDetector.SimpleOnScaleGestureListener {

		float currentScale;
		float currentMiddleX;
		float currentMiddleY;

		@Override
		public void onScaleEnd(ScaleGestureDetector detector) {

			ImageViewTouch imageView = getCurrentImageView();
			if (currentScale > imageView.mMaxZoom) {
//				imageView
//						.zoomToNoCenterWithAni(currentScale
//								/ imageView.mMaxZoom, 1, currentMiddleX,
//								currentMiddleY);
				currentScale = imageView.mMaxZoom;
				imageView.zoomToNoCenterValue(currentScale, currentMiddleX,
						currentMiddleY);
			} else if (currentScale < imageView.mMinZoom) {
//				imageView.zoomToNoCenterWithAni(currentScale,
//						imageView.mMinZoom, currentMiddleX, currentMiddleY);
				currentScale = imageView.mMinZoom;
				imageView.zoomToNoCenterValue(currentScale, currentMiddleX,
						currentMiddleY);
			} else {
				imageView.zoomToNoCenter(currentScale, currentMiddleX,
						currentMiddleY);
			}

			imageView.center(true, true);
			CorePreferences.DEBUG("mOnScale.close"+mOnScale);
			handler.sendEmptyMessageDelayed(1, 300);
		}

		@Override
		public boolean onScaleBegin(ScaleGestureDetector detector) {
			mOnScale = true;
			return true;
		}
		@Override
		public boolean onScale(ScaleGestureDetector detector, float mx, float my) {

			ImageViewTouch imageView = getCurrentImageView();
			float ns = imageView.getScale() * detector.getScaleFactor();

			currentScale = ns;
			currentMiddleX = mx;
			currentMiddleY = my;
			CorePreferences.DEBUG("currentScale:"+currentScale+",detector.isInProgress():"+detector.isInProgress());
			if (detector.isInProgress()) {
				if (currentScale > imageView.mMaxZoom) {
					currentScale = imageView.mMaxZoom;
					imageView.zoomToNoCenterValue(currentScale, currentMiddleX,
							currentMiddleY);
				} else if (currentScale < imageView.mMinZoom) {
					currentScale = imageView.mMinZoom;
					imageView.zoomToNoCenterValue(currentScale, currentMiddleX,
							currentMiddleY);
				} else {
					imageView.zoomToNoCenter(currentScale, currentMiddleX,
							currentMiddleY);
				}
				
			}
			return true;
		
		}
	}
	
	public void setCurrentPosition(int position){
		prePos = currPos;
		currPos = position;
		viewPager.setCurrentItem(currPos);
		if(useGallery){
			gallery.setSelection(currPos);
		}
	}
	public void setAlbumViewListener(AlumViewListener alumViewListener){
		this.alumViewListener = alumViewListener;
	}
	//outside event
	public interface AlumViewListener{
		public void onFullScreen(boolean fullScreen,int position);
		public void onChange(int position);
	}

    public boolean isFullScreen() {
        return isFullScreen;
    }

    public void setFullScreen(boolean f) {
        if (isFullScreen && !f) {
            hideControls();
            isFullScreen = false;
        }
        if (!isFullScreen && f) {
            showControls();
            isFullScreen = true;
        }
    }
}
